import tensorflow as tf
import numpy as np

#加载数据
mnist = tf.keras.datasets.mnist
(test_images, test_label), (train_images, train_label) = mnist.load_data()
#归一化
test_images = test_images / 255.0
train_images = train_images / 255.0

#模型搭建
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=(28, 28, 1)),
    tf.keras.layers.MaxPool2D(pool_size=2),
    tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation='relu'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='sigmoid'),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(10)
])

model.compile(
    optimizer='adam',
    loss=tf.keras.losses.SparseCategoricalCrossentropy(),
    metrics=['accuracy']
)

model.fit(train_images, train_label, epochs=10, batch_size=64)
model.save('tf_cnn.h5')

test_loss, test_acc = model.evaluate(test_images, test_label, verbose=2)
print('\nTest accuracy:', test_acc)